import type { FilterValue } from 'antd/es/table/interface';
import * as queryString from 'query-string';
import React from 'react';
import { usePersistFn, useRequest } from 'ahooks';
import { t } from '@lingui/macro';
import type { TablePaginationConfig } from 'antd/es/table';
import { Form } from 'antd';
import type { ScreenProp, SortProps } from '@/services/listTable';
import { getListTableData } from '@/services/listTable'; // getElementPermission,
import { dealColumnListPower } from '../utils';
import UseListTableHook from './useListTableHook';
import PovHook from './useListTablePov';
import type { IBaseParamsProp, IFormListMain } from './ListTable';
import {
  getPovInitValue,
  getTheNumberOfPovInARow,
  recordHowManyRowsOfPov,
  toArrayData,
} from '../utils/handlePovData';
import { getScreen } from '../utils/tableUtils';
import { ComparatorType } from '@/services/formList';
import type { IRequestBasicParameters } from '../utils/types';

const sortKey = {
  ascend: 'asc',
  descend: 'desc',
};

const getDefPovObj = (baseParams: IBaseParamsProp) => {
  const defPovObj: any = {
    pov: {}, // 默认值
    attr: {}, // 隐藏属性
  };
  baseParams?.povValList?.forEach((v) => {
    if (v.autoFill && v.value) {
      defPovObj.pov[v.alias] = v.value;
    }
    defPovObj.attr[v.alias] = {
      isDisplay: v.isDisplay,
    };
  });
  return defPovObj;
};

interface IListTableHookMainProp extends IFormListMain {
  lstContentRef: React.RefObject<HTMLDivElement>;
}

// eslint-disable-next-line max-lines-per-function
const ListTableHookMain = ({
  baseParams,
  bidSupport,
  type,
  lstContentRef,
}: IListTableHookMainProp) => {
  if (baseParams?.povValList && baseParams?.povValList?.length !== 0) {
    const defPovObj = getDefPovObj(baseParams);
    Object.assign(baseParams, { defPovObj });
  }
  // 仪表盘2.0协议逻辑
  if (bidSupport?.protocol?.version === '2.0') {
    const pov = {};
    bidSupport?.filters?.forEach((item) => {
      pov[item.name] = item.value;
    });
    Object.assign(baseParams || {}, { defPovObj: { pov, attr: {} } });
  }
  const query = baseParams?.elementDetail || queryString.parse(window.location.search);
  const [queryForm] = Form.useForm();
  const { elementName, folderId, path } = baseParams?.elementDetail || query;
  const baseScreen = query?.screen ? JSON.parse(query?.screen) : [];
  const basePov = query?.pov ? JSON.parse(query?.pov) : undefined;
  // 快速搜索值
  const { state, dispatch, tableForm } = UseListTableHook();
  const { state: povState, dispatch: povDispatch, getPovData, povForm } = PovHook();

  const { filterIcon } = state;
  const {
    loading,
    run,
    data: listConfigData,
  } = useRequest(getListTableData, {
    manual: true,
    formatResult: (res) => {
      const variableList = (res.variableList || []).map((item) => {
        return {
          ...item,
          isDisplay:
            (baseParams?.defPovObj && baseParams.defPovObj.attr[item.alias]?.isDisplay === false
              ? baseParams.defPovObj.attr[item.alias]?.isDisplay
              : true) && !(item.hidePageField === true),
          partType: 'variableList',
        };
      });
      return {
        ...res,
        // 将参数变量 variableList 塞到povList 中,因为使用太逻辑与pov 一致
        povList: (res.povList || [])
          .map((item) => {
            return {
              ...item,
              ...([11, 15].includes(item.valueType) && item.comparator === ComparatorType.EQUAL
                ? {
                    valueTypeMap: {
                      ...item.valueTypeMap,
                      defaultValue: Array.isArray(item.valueTypeMap.defaultValue)
                        ? item.valueTypeMap.defaultValue[0]
                        : item.valueTypeMap.defaultValue,
                    },
                  }
                : undefined),
              isDisplay:
                (baseParams?.defPovObj && baseParams.defPovObj.attr[item.alias]?.isDisplay === false
                  ? baseParams.defPovObj.attr[item.alias]?.isDisplay
                  : true) && !(item.hidePageField === true),
              partType: 'povList',
            };
          })
          .concat(variableList),
      };
    },
  });
  // const elementPermissionRequest = useRequest(getElementPermission, {
  //   manual: true,
  // });

  const pagination = React.useMemo(() => {
    const basePagination = {
      showSizeChanger: true,
      style: {
        margin: '12px 0',
      },
      showTotal: (total: number, range: [number, number]) => {
        return `${t`显示第`} ${range[0]}-${
          range[1]
        } ${t`项`}${t`结果`}，${t`共`} ${total} ${t`项`}`;
      },
    };
    if (listConfigData && !listConfigData.errorCode) {
      const {
        pageSize,
        pageNumber,
        page: current,
        total,
        customPageSize,
      } = listConfigData?.baseConfig || {};
      const sortCustomPageSize = customPageSize?.sort((a: any, b: any) => a - b);
      return {
        pageSize: pageSize || pageNumber,
        pageSizeOptions: sortCustomPageSize || ['10', '50', '100', '500', '1000'],
        current: current || 1,
        total,
        ...basePagination,
      } as TablePaginationConfig;
    }
    return undefined;
  }, [listConfigData]);

  // 判断筛选器是否出现小图标
  const onFilterFormData = usePersistFn((isSet: boolean) => {
    dispatch({
      type: 'setFilterIcon',
      filterIcon: isSet,
    });
  });
  // 查询数据
  const getData = usePersistFn(
    async (params?: {
      paginationParam?: {
        page?: number;
        pageSize?: number;
        sort?: SortProps[];
      };
      search?: string;
      isFirst?: boolean;
      screenList?: ScreenProp[];
      pov?: Record<string, unknown>;
      isFilter?: boolean; // 是否是通过筛选条件点击查询
    }) => {
      const {
        paginationParam = state.tableParameters,
        search,
        isFirst,
        screenList,
        pov,
        isFilter,
      } = params || {};
      const screenData =
        screenList || isFirst
          ? screenList || baseParams?.screen || baseScreen || []
          : state.filterIcon && !queryForm.getFieldsValue(true)?.list
          ? baseParams?.screen || baseScreen || []
          : filterIcon || isFilter
          ? getScreen(queryForm)
          : [];
      const povFieldVal = getPovData();
      const curPovParams = pov ? { ...povFieldVal, ...pov } : pov;
      let routePov = basePov;
      if (!curPovParams && isFirst && basePov) {
        routePov = Object.keys(routePov).reduce((init: Record<string, string>, key: string) => {
          const newObj = { ...init };
          newObj[key] = routePov[key];
          return newObj;
        }, {});
      }
      const povData =
        curPovParams || (isFirst ? routePov || baseParams?.defPovObj?.pov || {} : povFieldVal);
      const res = await run({
        ...state.tableParameters,
        ...paginationParam,
        elementName: elementName as string,
        folderId: folderId as string,
        path,
        screen: screenData,
        search: typeof search !== 'undefined' ? search : '',
        pov: toArrayData(povData),
        init: !!isFirst,
      });
      if (screenList) {
        queryForm.setFieldsValue({ list: screenData });
      }
      const newColumnList = await dealColumnListPower(res as any, 'columnList');
      const newPovList = await dealColumnListPower(res as any, 'povList');
      // 至少有一列配置可编辑
      const hasEditCol = res?.columnList?.some((item: any) => item.isEditable);
      // 是否可编辑行(不考虑行权限状态，只考虑全局开启允许编辑并且至少有一列配置可编辑场景)，用于判断整列编辑行是否显示
      const canEditRow = !!(res?.baseConfig?.allowEdit && hasEditCol);
      // 是否可添加行(不考虑行权限状态,只考虑全局配置开启允许新增删除按钮并且至少有一列配置可编辑场景)，用于判断添加行是否显示
      const canAddRow = !!(res?.baseConfig?.allowInsertDelete && hasEditCol);
      // 配置了关联模型或者配置了允许新增删除行，则整列删除按钮均显示 （因为关联模型后会有行删除权限判断，故将删除按钮显示，在根据行权限是否置灰）
      const canDeleteRow = !!(
        res?.baseConfig?.relevanceElementDetail?.elementName || res?.baseConfig?.allowInsertDelete
      );
      // 是否有配置了行按钮
      const hasLineButton = res?.baseConfig?.baseResult?.data.some(
        (current: any) => current?.position === 'LINE',
      );

      // 是否配置了快速搜索
      const hasQuickSearch = res?.columnList?.some((item: any) => item.quickSearch);

      // 请求基本参数记录
      const requestBasicParameters: IRequestBasicParameters = {
        elementName: elementName as string,
        folderId: folderId as string,
        path,
        screen: screenData,
        search: typeof search !== 'undefined' ? search : '',
        pov: toArrayData(povData),
      };

      if (isFirst) {
        dispatch({
          type: 'init',
          listConfigData: {
            ...res,
            columnList: newColumnList,
            povList: newPovList,
            isFirst: true,
            canEditRow,
            canAddRow,
            canDeleteRow,
            hasLineButton,
            hasQuickSearch,
          },
          tableParameters: paginationParam,
          requestBasicParameters,
        });
      } else {
        dispatch({
          type: 'init',
          listConfigData: {
            ...res,
            columnList: state.listConfigData ? state.listConfigData?.columnList : newColumnList,
            isFirst: false,
            povList: newPovList,
            canEditRow,
            canAddRow,
            canDeleteRow,
            hasLineButton,
            hasQuickSearch,
          },
          tableParameters: paginationParam,
          saveState: false,
          requestBasicParameters,
        });
      }

      onFilterFormData(!!screenData?.length);
      if (isFirst) {
        // 初始化pov
        const { numberOfPovInARow } = getTheNumberOfPovInARow(lstContentRef?.current?.offsetWidth);
        const povNumAndStatus = recordHowManyRowsOfPov(res?.povList, numberOfPovInARow);
        // povExtraAttributes:所有sheet的pov额外属性
        // newInitPovValue:所有sheet的pov默认值
        const { newInitPovValue, povExtraAttributes } = getPovInitValue(res?.povList, res);
        povDispatch({
          type: 'init',
          initData: {
            povHeightInfo: povNumAndStatus,
            povExtraParameters: povExtraAttributes as any,
            initPovValue: newInitPovValue,
            pageLoading: false,
            povIcon: false,
          },
        });
      } else {
        const { newInitPovValue, povExtraAttributes } = getPovInitValue(res?.povList, res);
        povDispatch({
          type: 'init',
          initData: {
            povIcon: false,
            povExtraParameters: povExtraAttributes,
            initPovValue: { ...povForm.getFieldsValue(), ...povData, ...newInitPovValue },
          } as any,
        });
        povForm.setFieldsValue({ ...povForm.getFieldsValue(), ...povData, ...newInitPovValue });
      }
      // 支持仪表盘展示协议，渲染完成（数据返回）回调
      if (bidSupport?.renderFinish) {
        bidSupport.renderFinish({ dataSource: res?.dataList || [] });
      }
    },
  );

  React.useEffect(() => {
    // if (!type) {
    //   elementPermissionRequest
    //     .run([{ elementName: elementName!, folderId, path, elementType: 'LST' }])
    //     .then((res) => {
    //       const permissionState = res ? res[0]?.permission || 'NoAccess' : 'error';
    //       dispatch({
    //         type: 'setEditedCol',
    //         permissionState,
    //       });
    //       if ([1, 2, 3, 4].includes(res[0]?.permission as number)) {
    //         getData({ isFirst: true }); // 首次打开
    //       }
    //     })
    //     .catch(() => {
    //       dispatch({
    //         type: 'setEditedCol',
    //         permissionState: 'error',
    //       });
    //     });
    // } else {
    //   getData({ isFirst: true });
    // }
    getData({ isFirst: true });
    if (baseParams?.getPov) baseParams.getPov(getPovData);
  }, []);

  // 查询监听
  React.useEffect(() => {
    if (bidSupport?.queryDataFlag && state.listConfigData?.isFirst !== undefined) {
      // 仪表盘2.0协议逻辑，再次刷新时将id 转换为别名，为兼容清单表其他本身pov值
      let curPov = {};
      if (bidSupport?.protocol?.version === '2.0') {
        state.listConfigData?.povList?.forEach((item) => {
          if (Reflect.has(baseParams?.defPovObj?.pov || {}, item.id)) {
            curPov[item.alias] = baseParams?.defPovObj?.pov?.[item.id];
          }
        });
      } else {
        curPov = baseParams?.defPovObj?.pov;
      }
      getData({ pov: curPov });
    }
  }, [bidSupport?.queryDataFlag]);

  // 列表分页和排序变化
  const tableChange = (
    p: TablePaginationConfig,
    _f: Record<string, FilterValue | null>,
    s: Record<string, any> | Record<string, any>[],
  ) => {
    const { current: page, pageSize } = p;
    const sortArr = Array.isArray(s) ? s : Object.keys(s).length !== 0 ? [s] : [];
    const sort = sortArr
      .map((v: Record<string, any>) => {
        return { colAlias: v.field, orderType: sortKey[v.order] };
      })
      .filter((v) => {
        return !!v.orderType;
      });
    getData({ paginationParam: { page, pageSize, sort } });
  };

  return {
    state,
    pagination,
    tableForm,
    query: baseParams?.elementDetail || query,
    povState,
    loading:  loading,// elementPermissionRequest.loading ||
    tableChange,
  };
};

export default ListTableHookMain;
